﻿using log4net;
using Oracle.ManagedDataAccess.Client;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using WMSSyncData.DAL;
using WMSSyncData.DAL.Oracle;
using WMSSyncData.DAL.SqlDB;
using WMSSyncData.Model.WMSModel;
using WMSSyncData.Utils;

namespace WMSSyncData.Core
{
    public class SyncRMERPData
    {

        private readonly ILog _logger = LogManager.GetLogger(typeof(SyncRMERPData));


        public static T Clone<T>(T RealObject)
        {
            using (Stream objectStream = new MemoryStream())
            {
                //利用 System.Runtime.Serialization序列化与反序列化完成引用对象的复制  
                IFormatter formatter = new BinaryFormatter();
                formatter.Serialize(objectStream, RealObject);
                objectStream.Seek(0, SeekOrigin.Begin);
                return (T)formatter.Deserialize(objectStream);
            }
        }

        public void SyncInStockRMData()
        {
            WMS_M_InStockRMDAL wMS_M_InStockRMDAL = new WMS_M_InStockRMDAL();


            WMS_M_InStockRMRowsDAL wMS_M_InStockRMRowsDAL = new WMS_M_InStockRMRowsDAL();

            WMS_T_InStockRMRowsDAL Storage_SNs = new WMS_T_InStockRMRowsDAL();
            //string sns = string.Empty; //获取仓库类型是201的仓库
            DataTable dtsn = Storage_SNs.GetStorageSN();
            string snss = "'xxx'";
            var list = wMS_M_InStockRMDAL.GetSyncData(snss);//获取未同步采购信息 非201 非发料
            if (list.Count > 0)         //非201处理
            {
                var rowsList = wMS_M_InStockRMRowsDAL.GetSyncData(snss); //获取未同步采购行信息 非201
                var rowLists = new List<WMS_T_InStockRMRows>(); //更新 采购行信息 非201
                foreach (var row in rowsList)
                {
                    bool RowIn = false;

                    foreach (var ListEntity in list)
                    {
                        if (row.RelatedBill == ListEntity.RelatedBill)  //根据EPR订单号给billno赋值
                        {
                            RowIn = true;
                            row.BillNo = ListEntity.BillNo;
                        }
                    }
                    if (RowIn)
                    {
                        rowLists.Add(row);
                    }
                }
                var result = new BaseSqlDBDAL<WMS_T_InStockRM>().InsertBatch(list); //更新WSM数据库采购主表
                var rowsResult = new BaseSqlDBDAL<WMS_T_InStockRMRows>().InsertBatch(rowLists); //更新WSM数据库采购行表

                if (result > 0)
                {
                    wMS_M_InStockRMRowsDAL.UpdateStatus(rowLists);
                    WMS_T_InStockRMRowsDAL wMS_T_InStockRMRows = new WMS_T_InStockRMRowsDAL();
                }

            }

            //最终收货
            SyncDeleteData(snss);
            SyncChangeData(dtsn); //同步有变化的数据

        } //采购入库

        public void SyncDeleteData(string type201)
        {
            WMS_M_InStockRMDAL wMS_M_InStockRMDAL = new WMS_M_InStockRMDAL();
            WMS_M_InStockRMRowsDAL wMS_M_InStockRMRowsDAL = new WMS_M_InStockRMRowsDAL();
            WMS_T_InStockRMRowsDAL wMS_T_InStockRMRows = new WMS_T_InStockRMRowsDAL();
            //最终收货
            var rowsList = wMS_M_InStockRMRowsDAL.GetSyncDeleteData(type201); //获取未同步采购行信息 非201
            //var list201 = wMS_M_InStockRMDAL.GetSyncDeleteRMData(type201);
            if (rowsList != null && rowsList.Count > 0)
            {

                var deleteListRow = wMS_T_InStockRMRows.getDeleteRows(rowsList);
                List<string> deletebillno = new List<string>();
                foreach (DataRow dr in deleteListRow.Rows)
                {
                    DataRow[] drSelect = deleteListRow.Select("billno='" + dr["billno"].ToString() + "'");
                    if (drSelect.Length == Convert.ToInt32(dr["billcount"]))
                    {
                        deletebillno.Add(dr["billno"].ToString());
                    }
                }
                if (deleteListRow != null && deleteListRow.Rows.Count > 0)
                {
                    var result = wMS_T_InStockRMRows.DeleteRowAndInfo(deleteListRow, deletebillno);
                    if (result)
                    {
                        //wMS_M_InStockRMRowsDAL.UpdateDeleteRowStatus(deleteListRow);
                        wMS_M_InStockRMRowsDAL.UpdateDeleteRowStatus(rowsList);
                    }
                }
                else
                {
                    wMS_M_InStockRMRowsDAL.UpdateDeleteRowStatus(rowsList);
                }
            }
        }

        public void SyncChangeData(DataTable dtsn)
        {
            WMS_M_InStockRMRowsDAL wMS_M_InStockRMDAL = new WMS_M_InStockRMRowsDAL();
            Tddev101DAL tddev101DAL = new Tddev101DAL();
            var wMS_T_InStockRMRowsDAL = new DAL.SqlDB.WMS_T_InStockRMRowsDAL();
            var dt = wMS_M_InStockRMDAL.GetChangeDT();

            var updateDt = dt.Clone();
            var noUpdateDt = dt.Clone();
            if (dt.Rows.Count > 0)
            {
                foreach (DataRow dr in dt.Rows)
                {
                    //OracleConnection conn = OracleDBHelper.Create();
                    //var tran = conn.BeginTransaction();

                    var boolSn = false;
                    var relationBill = dr["RelatedBill"].ToString();
                    var sn = dr["OrderNo"].ToString();
                    var rowNo = dr["RowNo"].ToString();
                    var status = dr["Status"].ToString();
                    var storage_SN = dr["Storage_SN"].ToString();
                    var planQty = Convert.ToDecimal(dr["PlanQty"]);
                    foreach (DataRow drsn in dtsn.Rows)  //判断是否仓库类型201
                    {
                        if (storage_SN == drsn["Storage_SN"].ToString())
                        {
                            boolSn = true;
                        }
                    }
                    if (boolSn) //如果仓库类型是201
                    {
                        //    var dtInstock = wMS_T_InStockRMRowsDAL.GetInStock(relationBill); //可以修改的订单
                        //    if (dtInstock != null&& dtInstock.Rows.Count>0)
                        //    {
                        //        var res = false;
                        //        if (status.EqualsOrdinalIgnoreCase("2"))//修改，修改对应的数量
                        //        {
                        //            res = wMS_T_InStockRMRowsDAL.UpdateInStockRowsPlanQty(dtInstock.Rows[0]["BillNo"].ToString(),Convert.ToInt32(planQty));
                        //        }
                        //        else if (status.EqualsOrdinalIgnoreCase("3"))//删除，我们这边把InStock状态修改为D
                        //        {
                        //            res = wMS_T_InStockRMRowsDAL.UpdateInStockStatus(dtInstock.Rows[0]["BillNo"].ToString());
                        //        }
                        //        if (res)
                        //        {
                        //            updateDt.Rows.Add(dr.ItemArray);
                        //        }
                        //    }
                        //    else//同步过来的订单已经进行了操作，则不修改
                        //    {
                        //        noUpdateDt.Rows.Add(dr.ItemArray);
                        //    }
                    }
                    else //仓库类型不是201
                    {
                        var item = wMS_T_InStockRMRowsDAL.Get(relationBill, sn, rowNo);
                        if (item != null)
                        {
                            var res = false;
                            if (status.EqualsOrdinalIgnoreCase("2"))//修改，修改对应的数量
                            {
                                res = wMS_T_InStockRMRowsDAL.UpdateInStockRMRowsPlanQty(item.BillNo, planQty, item.RowNo);
                            }
                            else if (status.EqualsOrdinalIgnoreCase("3"))//删除，我们这边把OutStock状态修改为D
                            {
                                res = wMS_T_InStockRMRowsDAL.UpdateInStockRMStatus(item.BillNo, item.RowNo);
                            }
                            if (res)
                            {
                                updateDt.Clear();
                                updateDt.Rows.Add(dr.ItemArray);
                                tddev101DAL.UpdateStatus(updateDt);
                            }
                        }
                        else//同步过来的订单已经进行了操作，则不修改
                        {
                            noUpdateDt.Clear();
                            noUpdateDt.Rows.Add(dr.ItemArray);
                            tddev101DAL.UpdateText(noUpdateDt);
                        }
                    }
                }

                //if (updateDt.Rows.Count > 0)
                //{
                //    tddev101DAL.UpdateStatus(updateDt);
                //}

                //if (noUpdateDt.Rows.Count > 0)
                //{
                //    tddev101DAL.UpdateText(noUpdateDt);
                //}

            }

        }  //已同步数据有修改或删除的

        public void SyncOutStockRMData()
        {
            WMS_M_OutStockRMDAL wMS_M_OutStockRMDAL = new WMS_M_OutStockRMDAL();
            WMS_M_OutStockRMRowsDAL wMS_M_OutStockRMRowsDAL = new WMS_M_OutStockRMRowsDAL();
            WMS_T_InStockRMRowsDAL Storage_SNs = new WMS_T_InStockRMRowsDAL();

            var list = wMS_M_OutStockRMDAL.GetSyncOutStockData();//获取未同步采购信息 非201 非发料

            if (list.Count > 0)         //非201处理
            {
                var rowsList = wMS_M_OutStockRMRowsDAL.GetSyncData(); //获取未同步采购行信息 非201
                var rowLists = new List<WMS_T_OutStockRMRows>(); //更新 采购行信息 非201
                foreach (var row in rowsList)
                {
                    bool RowIn = false;

                    foreach (var ListEntity in list)
                    {
                        if (row.RelatedBill == ListEntity.RelatedBill)  //根据EPR订单号给billno赋值
                        {
                            RowIn = true;
                            row.BillNo = ListEntity.BillNo;
                        }
                    }
                    if (RowIn)
                    {
                        rowLists.Add(row);
                    }
                }
                var result = new BaseSqlDBDAL<WMS_T_OutStockRM>().InsertBatch(list); //更新WSM数据库采购主表
                var rowsResult = new BaseSqlDBDAL<WMS_T_OutStockRMRows>().InsertBatch(rowLists); //更新WSM数据库采购行表

                if (rowsResult > 0)
                {
                    wMS_M_OutStockRMRowsDAL.UpdateStatus(rowLists);
                }
            }

            SyncDeleteOutData();
            //SyncChangeData(dtsn); //同步有变化的数据

        } //采购入库
        public void SyncDeleteOutData()
        {
            WMS_M_OutStockRMDAL wMS_M_OutStockRMDAL = new WMS_M_OutStockRMDAL();

            WMS_M_OutStockRMRowsDAL wMS_M_OutStockRMRowsDAL = new WMS_M_OutStockRMRowsDAL();
            //最终收货
            var rowsList = wMS_M_OutStockRMRowsDAL.GetSyncDeleteData(); //获取未同步采购行信息 非201

            if (rowsList != null && rowsList.Count > 0)
            {

                var deleteListRow = wMS_M_OutStockRMRowsDAL.getDeleteRows(rowsList);
                List<string> deletebillno = new List<string>();
                foreach (DataRow dr in deleteListRow.Rows)
                {
                    DataRow[] drSelect = deleteListRow.Select("billno='" + dr["billno"].ToString() + "'");
                    if (drSelect.Length == Convert.ToInt32(dr["billcount"]))
                    {
                        deletebillno.Add(dr["billno"].ToString());
                    }
                }
                if (deleteListRow != null && deleteListRow.Rows.Count > 0)
                {
                    var result = wMS_M_OutStockRMRowsDAL.DeleteRowAndInfo(deleteListRow, deletebillno);
                    if (result)
                    {
                        wMS_M_OutStockRMRowsDAL.UpdateDeleteRowStatus(deleteListRow);
                    }
                }
            }

        }


        public void SyncSFPData() //半成品领料
        {
            Tddev111DAL tddev111DAL = new Tddev111DAL();
            WMS_M_InStockRMDAL wMS_M_InStockRMDAL = new WMS_M_InStockRMDAL();

            WMS_T_InventoryDAL wMS_T_InventoryDAL = new WMS_T_InventoryDAL();
            WMS_T_InventoryHistoryDAL wMS_T_InventoryHistoryDAL = new WMS_T_InventoryHistoryDAL();

            var OutStockList = tddev111DAL.GetSPFData();   //获取半成品领料出库数据
            List<WMS_T_OutStock> lists = new List<WMS_T_OutStock>(); //新增入outStock表的数据
            List<WMS_T_OutStockRows> listRows = new List<WMS_T_OutStockRows>(); //新增入outStock表行的数据
            List<WMS_T_InventoryHistory> listInvenHis = new List<WMS_T_InventoryHistory>(); //新增履历表数据

            var sFPDt = wMS_M_InStockRMDAL.GetSyncSFPData();

            if (sFPDt != null && sFPDt.Rows.Count > 0)
            {
                foreach (DataRow dr in sFPDt.Rows)
                {
                    var Storage_SN = dr["Storage_SN"].ToString();
                    var PN = dr["PartNumber"].ToString();
                    var PQ = Convert.ToDecimal(dr["Qty"].ToString());
                    var billno = dr["BillNO"].ToString();

                    var excRes = wMS_T_InventoryDAL.UpdateQty(Storage_SN, PN, PQ);

                    if (excRes > 0)  //如果库存表数据修改成功
                    {
                        var OutStocksList = OutStockList.Where(x => x.BillNo.EqualsOrdinalIgnoreCase(billno)).ToList();
                        foreach (var outstock in OutStocksList)
                        {
                            lists.Add(outstock);
                        }

                        var outstockRow = new WMS_T_OutStockRows()
                        {
                            Guid = dr["GUID"].ToString(),
                            BillNo = billno,
                            RowNo = Convert.ToInt32(dr["RowNo"].ToString()),
                            ProductNumber = dr["PartNumber"].ToString(),
                            SelectQty = Convert.ToInt32(PQ),
                            RealQty = Convert.ToInt32(PQ),

                            SN = Convert.ToInt32(dr["SN"].ToString())
                        };
                        listRows.Add(outstockRow);

                        var inventoryHis = new WMS_T_InventoryHistory()
                        {
                            Guid = Guid.NewGuid().ToString(),
                            Storage_SN = Storage_SN,
                            Area_SN = "0",
                            Location_SN = "0",
                            PartNumber = PN,
                            Qty = -PQ,
                            CreateTime = DateTime.Now,
                            Creator = dr["Creator"].ToString(),
                            IO = "O",
                            RelatedBill1 = dr["RelatedBill"].ToString(),
                            RelatedBill2 = dr["BillNO"].ToString()
                        };
                        listInvenHis.Add(inventoryHis);
                    }
                }
                new BaseSqlDBDAL<WMS_T_OutStock>().InsertBatch(lists);   //插入出库信息
                new BaseSqlDBDAL<WMS_T_OutStockRows>().InsertBatch(listRows);   //插入出库行信息
                new BaseSqlDBDAL<WMS_T_InventoryHistory>().InsertBatch(listInvenHis); //插入履历信息
            }

        }
        public void SyncInFPData()  //半成品入库
        {
            WMS_M_InStockDAL wMS_M_InStockDAL = new WMS_M_InStockDAL();
            var inventoryDT = wMS_M_InStockDAL.GetInventoryInfo("半成品入库");
            List<WMS_T_InStock> listwIS = new List<WMS_T_InStock>();
            if (inventoryDT != null)
            {

                //取重复
                var distinctTable = inventoryDT.Clone();
                //DataView dv = new DataView(inventoryDT);
                //distinctTable = dv.ToTable(true, new string[]{ "BillNO" });
                distinctTable = inventoryDT.AsEnumerable().Cast<DataRow>().GroupBy(p => p.Field<string>("BillNO")).Select(p => p.FirstOrDefault()).CopyToDataTable();
                // 生成需要输入的对象
                foreach (DataRow dr in distinctTable.Rows)
                {
                    WMS_T_InStock InStockEntity = new WMS_T_InStock();
                    InStockEntity.Guid = Guid.NewGuid().ToString();
                    InStockEntity.BillNo = dr["BillNO"].ToString();
                    InStockEntity.RelatedBill = dr["RelatedBill"] == null ? "" : dr["RelatedBill"].ToString();
                    InStockEntity.Status = "1";  //半成品入库后直接同步到ERP
                    InStockEntity.BillType = "半成品入库";
                    InStockEntity.Storage_SN = dr["Storage_SN"].ToString();
                    InStockEntity.Creator = dr["creator"].ToString();
                    InStockEntity.CreateTime = Convert.ToDateTime(dr["CreateTime"].ToString());
                    listwIS.Add(InStockEntity);
                }
                var result = new BaseSqlDBDAL<WMS_T_InStock>().InsertBatch(listwIS);

                var inventoryRes = InsertInventoryDT(inventoryDT);

            }
        }
        public void SyncProductReturnData()//生产退料
        {
            WMS_M_InStockRMDAL wMS_M_InStockRMDAL = new WMS_M_InStockRMDAL();
            WMS_M_InStockRMRowsDAL wMS_M_InStockRMRowsDAL = new WMS_M_InStockRMRowsDAL();

            var ListPR = wMS_M_InStockRMDAL.GetPRData();//获取生产退料数据
            var ListPRRow = wMS_M_InStockRMRowsDAL.GetPRData();
            if (ListPR != null && ListPR.Count > 0)
            {
                var result = new BaseSqlDBDAL<WMS_T_InStockRM>().InsertBatch(ListPR);   //插入入库信息
                var resultRow = new BaseSqlDBDAL<WMS_T_InStockRMRows>().InsertBatch(ListPRRow);   //插入入库行信息

                if (result > 0)
                {
                    wMS_M_InStockRMRowsDAL.UpdatePRStatus(ListPRRow);   //修改中间库表状态
                }
            }
        }

        public void SyncProductOfMaterialsData()//生产领料
        {

            WMS_M_OutStockRMDAL wMS_M_OutStockRMDAL = new WMS_M_OutStockRMDAL();
            WMS_M_OutStockRMRowsDAL wMS_M_OutStockRMRowsDAL = new WMS_M_OutStockRMRowsDAL();

            var ListPOM = wMS_M_OutStockRMDAL.GetSyncData("领料出库");//获取生产退料数据
            var ListPOMRow = wMS_M_OutStockRMRowsDAL.GetSyncData("领料出库");//获取生产退料行数据
            if (ListPOM != null && ListPOM.Count > 0)
            {
                var result = new BaseSqlDBDAL<WMS_T_OutStockRM>().InsertBatch(ListPOM);   //插入出库信息
                var resultRow = new BaseSqlDBDAL<WMS_T_OutStockRMRows>().InsertBatch(ListPOMRow);   //插入出库行信息

                if (result > 0)
                {
                    wMS_M_OutStockRMRowsDAL.UpdatePOMStatus(ListPOMRow);   //修改中间库表状态
                }
            }
        }

        /// <summary>
        /// MES叫料
        /// </summary>
        public void MesCallMaterials()
        {
            WMS_M_OutStockRMDAL wMS_M_OutStockRMDAL = new WMS_M_OutStockRMDAL();
            WMS_M_OutStockRMRowsDAL wMS_M_OutStockRMRowsDAL = new WMS_M_OutStockRMRowsDAL();

            var heads = wMS_M_OutStockRMDAL.GetMesHead("领料出库");
            var details = wMS_M_OutStockRMRowsDAL.GetMesDetail("领料出库");

            if (heads.Count > 0 && details.Count > 0)
            {
                var result = new BaseSqlDBDAL<WMS_T_OutStockRM>().InsertBatch(heads);
                var resultRow = new BaseSqlDBDAL<WMS_T_OutStockRMRows>().InsertBatch(details);

                if (result > 0)
                {
                    wMS_M_OutStockRMDAL.CloseMesHead(heads);
                }
            }
        }


        public void SyncProductOfMaterialsByERPBomData()//从ERP BOM表获取生产领料
        {

            WMS_M_OutStockRMDAL wMS_M_OutStockRMDAL = new WMS_M_OutStockRMDAL();
            WMS_M_OutStockRMRowsDAL wMS_M_OutStockRMRowsDAL = new WMS_M_OutStockRMRowsDAL();
            WMS_T_InStockRMRowsDAL Storage_SNs = new WMS_T_InStockRMRowsDAL();

            string sns = string.Empty;
            DataTable dtsn = Storage_SNs.GetStorage101SN();
            if (dtsn != null & dtsn.Rows.Count > 0)
            {
                StringBuilder sb = new StringBuilder();
                foreach (DataRow dr in dtsn.Rows)
                {
                    sb.Append("'" + dr["Storage_SN"].ToString() + "',");
                }
                sns = sb.ToString().Substring(0, sb.Length - 1);
            }

            var ListPOM = wMS_M_OutStockRMDAL.GetSyncRMByERPBOMData(sns);//获取生产退料数据
            var ListPOMRow = wMS_M_OutStockRMRowsDAL.GetSyncRMByERPBOMData(sns);//获取生产退料行数据

            if (ListPOM != null && ListPOM.Count > 0)
            {
                List<WMS_T_OutStockRMRows> listRows = new List<WMS_T_OutStockRMRows>();
                foreach (WMS_T_OutStockRMRows OutRowEntity in ListPOMRow)
                {
                    bool RowIn = false;
                    foreach (WMS_T_OutStockRM OutEntity in ListPOM)
                    {
                        if (OutEntity.RelatedBill == OutRowEntity.RelatedBill)
                        {
                            RowIn = true;
                            OutRowEntity.BillNo = OutEntity.BillNo;
                        }
                    }
                    if (RowIn)
                    {
                        listRows.Add(OutRowEntity);
                    }
                }

                var result = new BaseSqlDBDAL<WMS_T_OutStockRM>().InsertBatch(ListPOM);   //插入出库信息
                var resultRow = new BaseSqlDBDAL<WMS_T_OutStockRMRows>().InsertBatch(listRows);   //插入出库行信息

                if (result > 0)
                {
                    wMS_M_OutStockRMRowsDAL.UpdateBOMStatus(listRows);   //修改中间库表状态
                }
            }

            var ListPOMRowUpdate = wMS_M_OutStockRMRowsDAL.GetSyncRMUpdateByERPBOMData(sns);
            if (ListPOMRowUpdate != null && ListPOMRowUpdate.Count > 0)
            {
                DataTable CanUpdateDt = Storage_SNs.GetUpdateBOMOutStockRowData(ListPOMRowUpdate);
                if (CanUpdateDt != null && CanUpdateDt.Rows.Count > 0)
                {
                    List<WMS_T_OutStockRMRows> CanUpdateList = new List<WMS_T_OutStockRMRows>();
                    foreach (WMS_T_OutStockRMRows entity in ListPOMRowUpdate)
                    {
                        bool isRowIn = false;
                        foreach (DataRow dr in CanUpdateDt.Rows)
                        {
                            if (entity.RelatedBill == dr["RelatedBill"].ToString() && entity.RowNo.ToString() == dr["RowNo"].ToString())
                            {
                                isRowIn = true;
                            }
                        }
                        if (isRowIn)
                        {
                            CanUpdateList.Add(entity);
                        }
                    }
                    var resultUpdate = Storage_SNs.UpdateBOMRowInfo(CanUpdateList);
                    if (resultUpdate)
                    {
                        wMS_M_OutStockRMRowsDAL.UpdateBOMStatus(CanUpdateList);   //修改中间库表状态
                    }
                }
            }
            var ListPOMRowDelete = wMS_M_OutStockRMRowsDAL.GetSyncRMDeleteByERPBOMData(sns);
            if (ListPOMRowDelete != null && ListPOMRowDelete.Count > 0)
            {

            }

        }


        public void SyncUpdateMdcDatVStorageData()//退料明细更新MdcDatVStorage
        {
            WMS_M_InStockRMDetails wMS_M_InStockRMDetails = new WMS_M_InStockRMDetails();
            WMS_T_InStorckRMRowDetailsDAL wMS_T_InStorckRMRowDetailsDAL = new WMS_T_InStorckRMRowDetailsDAL();
            var MDDt = wMS_M_InStockRMDetails.getUpdateDate();
            if (MDDt != null && MDDt.Rows.Count > 0)
            {
                var result = wMS_T_InStorckRMRowDetailsDAL.UpdateMdcDatVStorage(MDDt);
                if (result > 0)
                {
                    wMS_M_InStockRMDetails.UpdateMInStockStatus(MDDt);
                }
            }

        }


        public void SyncUpdateInventoryData()// 
        {
            WMS_M_OutStockRMDAL wMS_M_OutStockRMDAL = new WMS_M_OutStockRMDAL();
            WMS_T_OutStorckRMRowDetailsDAL wMS_T_OutStorckRMRowDetailsDAL = new WMS_T_OutStorckRMRowDetailsDAL();
            var MDDt = wMS_M_OutStockRMDAL.GetInverUpdateDate();
            if (MDDt != null && MDDt.Rows.Count > 0)
            {
                DataTable UpdateInvernAllDt = wMS_T_OutStorckRMRowDetailsDAL.getUpdateInvernAll(MDDt);
                List<DataRow> updateInverList = new List<DataRow>();
                List<WMS_T_Inventory> updateInverRowList = new List<WMS_T_Inventory>();
                List<WMS_T_Inventory> delteInverRowList = new List<WMS_T_Inventory>();
                if (UpdateInvernAllDt != null && UpdateInvernAllDt.Rows.Count > 0)
                {
                    for (int i = 0; i < MDDt.Rows.Count; i++)
                    {
                        var UpdateInverDrRows = UpdateInvernAllDt.Compute("sum(Qty)", " PartNumber='" + MDDt.Rows[i]["T$ITEM"].ToString() + "' and Storage_SN='" + MDDt.Rows[i]["T$CWAR"].ToString() + "'");
                        if (UpdateInverDrRows != DBNull.Value)
                        {
                            decimal QtyAll = Convert.ToDecimal(UpdateInverDrRows);
                            decimal QtyReduce = Convert.ToDecimal(MDDt.Rows[i]["T$qstk"]);
                            foreach (DataRow drupdate in updateInverList)
                            {
                                if (drupdate["T$ITEM"].ToString() == MDDt.Rows[i]["T$ITEM"].ToString() && drupdate["T$CWAR"].ToString() == MDDt.Rows[i]["T$CWAR"].ToString())
                                {
                                    QtyReduce = QtyReduce + Convert.ToDecimal(drupdate["T$qstk"]);
                                }
                            }
                            if ((QtyAll - QtyReduce) > 0)
                            {
                                updateInverList.Add(MDDt.Rows[i]);
                            }
                        }
                    }
                    List<DataRow> listHave = new List<DataRow>();
                    foreach (DataRow drupdate in updateInverList)
                    {
                        bool goOn = true;
                        foreach (DataRow dr in listHave)
                        {
                            if (dr["T$ITEM"].ToString() == drupdate["T$ITEM"].ToString() && dr["T$CWAR"].ToString() == drupdate["T$CWAR"].ToString())
                            {
                                goOn = false;
                            }
                        }
                        if (goOn)
                        {
                            decimal QtyWillReduce = 0;
                            foreach (DataRow drWR in updateInverList)
                            {
                                if (drWR["T$ITEM"].ToString() == drupdate["T$ITEM"].ToString() && drWR["T$CWAR"].ToString() == drupdate["T$CWAR"].ToString())
                                {
                                    QtyWillReduce = QtyWillReduce + Convert.ToDecimal(drWR["T$qstk"]);
                                }
                            }
                            DataRow[] drs = UpdateInvernAllDt.Select("PartNumber='" + drupdate["T$ITEM"].ToString() + "' and Storage_SN='" + drupdate["T$CWAR"].ToString() + "'");

                            foreach (DataRow drRow in drs)
                            {

                                decimal QtyRow = Convert.ToDecimal(drRow["Qty"]);
                                if (QtyWillReduce > 0)
                                {
                                    WMS_T_Inventory wMS_T_Inventory = new WMS_T_Inventory();
                                    wMS_T_Inventory.Guid = drRow["Guid"].ToString();
                                    if (QtyWillReduce > QtyRow)
                                    {
                                        QtyWillReduce = QtyWillReduce - QtyRow;
                                        wMS_T_Inventory.Qty = 0;
                                        delteInverRowList.Add(wMS_T_Inventory);
                                    }
                                    else
                                    {

                                        wMS_T_Inventory.Qty = QtyRow - QtyWillReduce;
                                        QtyWillReduce = 0;
                                        updateInverRowList.Add(wMS_T_Inventory);
                                    }
                                }
                            }
                        }
                        listHave.Add(drupdate);
                    }
                    if (updateInverRowList.Count > 0 || delteInverRowList.Count > 0)
                    {
                        var resultInt = wMS_T_OutStorckRMRowDetailsDAL.UpdateInvernAll(updateInverRowList, delteInverRowList);
                        if (resultInt > 0)
                        {
                            wMS_M_OutStockRMDAL.UpdateStatus(updateInverList);
                        }
                    }
                }
            }

        }

        public bool InsertInventoryDT(DataTable dt)
        {
            var result = false;
            WMS_T_InStorckRMRowDetailsDAL wMS_T_InStorckRMRowDetailsDAL = new WMS_T_InStorckRMRowDetailsDAL();


            try
            {
                var inventoryListNew = new List<WMS_T_Inventory>();
                var inventoryListUpdate = new List<WMS_T_Inventory>();
                var inventoryHisList = new List<WMS_T_InventoryHistory>();
                if (dt.Rows.Count > 0)
                {
                    foreach (DataRow dr in dt.Rows)
                    {
                        var PartNumber = dr["PartNumber"].ToString();
                        var Version = dr["EXT1"].ToString();
                        var DateCode = dr["EXT2"].ToString();

                        var InvenDT = wMS_T_InStorckRMRowDetailsDAL.GetInventoryInfoByConditon(PartNumber, Version, DateCode);
                        if (InvenDT != null && InvenDT.Rows.Count > 0)//判断库存中是否存在 
                        {

                        }
                        else  //不存在
                        {
                            var inventory = new WMS_T_Inventory()
                            {
                                Guid = Guid.NewGuid().ToString(),
                                Storage_SN = dr["Storage_SN"].ToString(),
                                Area_SN = "0",
                                Location_SN = "0",
                                PartNumber = PartNumber,
                                EnterTime = DateTime.Now,
                                Qty = Convert.ToDecimal(dr["Qty"]),
                                Version = Version,
                                DateCode = DateCode,
                                Status = "1",
                                Unit = dr["Unit"].ToString(),
                            };
                            inventoryListNew.Add(inventory);
                        }
                        var inventoryHis = new WMS_T_InventoryHistory()
                        {
                            Guid = Guid.NewGuid().ToString(),
                            Storage_SN = "000",
                            Area_SN = "0",
                            Location_SN = "0",
                            PartNumber = dr["PartNumber"].ToString(),
                            Qty = Convert.ToDecimal(dr["Qty"]),
                            CreateTime = DateTime.Now,
                            Creator = dr["Creator"].ToString(),
                            IO = "I",
                            RelatedBill1 = dr["RelatedBill"].ToString(),
                            RelatedBill2 = dr["BillNO"].ToString()
                        };
                        inventoryHisList.Add(inventoryHis);
                    }
                    new BaseSqlDBDAL<WMS_T_Inventory>().InsertBatch(inventoryListNew);
                    new BaseSqlDBDAL<WMS_T_InventoryHistory>().InsertBatch(inventoryHisList);
                }

                result = true;
            }
            catch (Exception ex)
            {

            }

            return result;
        }


    }
}
